import type { LoadingInstance } from 'element-plus/es/components/loading/src/loading'
import { ElLoading } from 'element-plus'

/**
 * 通用文件下载方法
 *
 * @param apiFunction API请求函数
 * @param params API请求参数
 * @param fileName 下载的文件名
 * @param fileType 文件类型，默认为Excel
 * @param loadingOptions 加载动画配置
 * @param loadingOptions.lock
 * @param loadingOptions.text
 * @param loadingOptions.spinner
 * @param loadingOptions.background
 */
export async function downloadFile(
  apiFunction: (params: any) => Promise<any>,
  params: any,
  fileName: string,
  fileType: string = 'application/vnd.ms-excel',
  loadingOptions?: {
    lock?: boolean
    text?: string
    spinner?: string
    background?: string
  },
) {
  const defaultLoadingOptions = {
    lock: true,
    text: '下载中...',
    spinner: '',
    background: 'rgba(0, 0, 0, 0.1)',
    ...loadingOptions,
  }

  let loading: LoadingInstance | undefined
  try {
    loading = ElLoading.service(defaultLoadingOptions)

    const res = await apiFunction(params)

    const link = document.createElement('a')
    const blob = new Blob([res], { type: fileType })
    link.style.display = 'none'
    link.href = URL.createObjectURL(blob)
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(link.href)
  } catch (error) {
    console.error('Download failed:', error)
    throw error
  } finally {
    loading?.close()
  }
}
